package com.jhc.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jhc.bo.UserSaveDetails;
import com.jhc.dto.*;
import com.jhc.entity.*;
import com.jhc.mapper.*;
import com.jhc.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jhc.utils.CheckType;
import com.jhc.utils.JHC;
import com.jhc.vo.DateVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 7s检查记录表  服务实现类
 * </p>
 *
 * @author zfm
 * @since 2019-12-03
 */
@Service
public class Ise7sInspectServiceImpl extends ServiceImpl<Ise7sInspectMapper, Ise7sInspect> implements IIse7sInspectService {

    @Autowired
    private Ise7sInspectMapper ise7sInspectMapper;

    @Autowired
    private IBacTermService termService;

    @Autowired
    private IseScheduleMapper scheduleMapper;

    @Autowired
    private UserSaveDetails userSaveDetails;

    @Autowired
    private IseInspectionMapper iseInspectionMapper;

    @Autowired
    private BacTrainingRoomMapper trainingRoomMapper;

    @Autowired
    private CmsTeacherMapper teacherMapper;

    @Autowired
    private IIseDormInspectService dormInspectService;

    @Autowired
    private ICmsTeacherService teacherService;

    @Autowired
    private IIseInspectionService inspectionService;

    @Autowired
    private IIseScheduleService scheduleService;


    @Autowired
    private IseImagesMapper imagesMapper;

    @Autowired
    private CmsUserMapper cmsUserMapper;

    @Autowired
    private ICmsUserService cmsUserService;

    /**
     * 查询7s检查列表
     *
     * @param ise7sInspectSearchDto
     * @return
     */
    @Override
    public IPage<Ise7sInspectViewDto> get7sInspect(Ise7sInspectSearchDto ise7sInspectSearchDto) {
        //获取当前日期
        Date nowDate = JHC.removeTime(new Date());
        //查询值班人员
        String username = userSaveDetails.getCmsUser().getNumber();
        System.out.println(username);
        IseSchedule schedule = scheduleService.isSchedule(username,nowDate);
        System.out.println(schedule);
        //若不值班就返回空分页
        if (schedule == null){
            return new Page<>(ise7sInspectSearchDto.getCurrentPage(),ise7sInspectSearchDto.getPageSize());
        }
        //查询教学列表和已检查id
        List<Object> itemCheckIds = inspectionService.getItemIds(nowDate,CheckType.ISE7S.getCode());
        //判断是否需要查询检查
        if (itemCheckIds.size()==0&&ise7sInspectSearchDto.getIsWrited()!=null&&ise7sInspectSearchDto.getIsWrited()){
            return new Page<>(ise7sInspectSearchDto.getCurrentPage(),ise7sInspectSearchDto.getPageSize());
        }
        //模糊查询老师姓名
        List<Object> teachList = null;
        if (StringUtils.isNotEmpty(ise7sInspectSearchDto.getResponsibleName())){
            teachList = cmsUserService.getUserListByLikeName(ise7sInspectSearchDto.getResponsibleName())
                    .stream().map(item -> item.getNumber()).collect(Collectors.toList());
            if (teachList.size()==0){
                return new Page<>(ise7sInspectSearchDto.getCurrentPage(),ise7sInspectSearchDto.getPageSize());
            }
        }
        Page page = new Page(ise7sInspectSearchDto.getCurrentPage(),ise7sInspectSearchDto.getPageSize());
        //条件查询实训室
        IPage<BacTrainingRoom> roomIPage = trainingRoomMapper.selectPage(page,new QueryWrapper<BacTrainingRoom>()
                .lambda().isNotNull(BacTrainingRoom::getTrainingcenterId)
                .in(ise7sInspectSearchDto.getIsWrited()!=null&&ise7sInspectSearchDto.getIsWrited(),BacTrainingRoom::getId,itemCheckIds)
                .notIn(itemCheckIds.size()!=0&&ise7sInspectSearchDto.getIsWrited()!=null&&!ise7sInspectSearchDto.getIsWrited(),BacTrainingRoom::getId,itemCheckIds)
                .in(StringUtils.isNotEmpty(ise7sInspectSearchDto.getResponsibleName()),BacTrainingRoom::getResponsibleNumber,teachList)
                .like(StringUtils.isNotEmpty(ise7sInspectSearchDto.getRoomName()),BacTrainingRoom::getRoomName,ise7sInspectSearchDto.getRoomName()));
        System.out.println(roomIPage.getRecords());
        //标记是否已填写
        List<Ise7sInspectViewDto> list7s = new ArrayList<>();
        roomIPage.getRecords().stream().forEach(item ->{
            Ise7sInspectViewDto ise7sInspectViewDto = new Ise7sInspectViewDto();
            BeanUtils.copyProperties(item,ise7sInspectViewDto);
            System.out.println(ise7sInspectViewDto);
            if (itemCheckIds.contains(ise7sInspectViewDto.getId())){
                ise7sInspectViewDto.setIsWrited(true);
                IseInspection inspection = iseInspectionMapper.selectOne(new QueryWrapper<IseInspection>().lambda()
                        .eq(IseInspection::getItemCheckId,item.getId())
                        .eq(IseInspection::getDutyDate,JHC.toDateString(nowDate))
                        .eq(IseInspection::getCheckType,CheckType.ISE7S.getCode()));
                ise7sInspectViewDto.setInspectId(inspection.getId());
            }
            //查询对应实验员老师姓名
            CmsUser teacher = cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber,item.getResponsibleNumber()));
            ise7sInspectViewDto.setResponsibleName(teacher.getName());
            ise7sInspectViewDto.setWeek(schedule.getWeek());
            list7s.add(ise7sInspectViewDto);
        });
        IPage<Ise7sInspectViewDto> page7s = new Page<>();
        BeanUtils.copyProperties(roomIPage,page7s);
        page7s.setRecords(list7s);
        return page7s;
    }

    /**
     * 查询7s检查进度条
     *
     * @return
     */
    @Override
    public Map<String, Object> getProgress() {
        //获取当前日期
        Date nowDate = JHC.removeTime(new Date());
        //查询值班人员
        String username = userSaveDetails.getCmsUser().getNumber();
        IseSchedule schedule = scheduleService.isSchedule(username,nowDate);
        //若不值班就返回null
        if (schedule == null){
            return null;
        }
        //查询实训室数据条数
        Integer all7sInspect = trainingRoomMapper.selectCount(new QueryWrapper<BacTrainingRoom>().lambda()
                .isNotNull(BacTrainingRoom::getTrainingcenterId));
        //查询检查总表数据条数
        Integer finish7sInspect = iseInspectionMapper.selectCount(new QueryWrapper<IseInspection>().lambda()
                .eq(IseInspection::getDutyDate,JHC.toDateString(new Date()))
                .eq(IseInspection::getCheckType,CheckType.ISE7S.getCode()));
        //构造返回对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("allProgress",all7sInspect);
        resultMap.put("finishProgress",finish7sInspect);
        return resultMap;
    }

    /**
     * 查询已填写的7s检查信息
     *
     * @param searchDto
     * @return
     */
    @Override
    public IPage<Finish7sViewDto> getFinish7s(All7sSearchDto searchDto,Boolean type) {
        //获取当前用户名
        String username = null;
        String feedback = null;
        if (type!=null&&type){
            username = userSaveDetails.getCmsUser().getNumber();
        }
        if (type == null){
            feedback = userSaveDetails.getCmsUser().getNumber();
        }
        //获取当前学期开始和结束时间
        Date date = new Date();
        DateVo dateVo = termService.getTermDate(date);
        if (searchDto.getStartDate()==null){
            searchDto.setStartDate(dateVo.getStartDate());
        }
        if (searchDto.getEndDate()==null){
            searchDto.setEndDate(dateVo.getEndDate());
        }
        //查询默认当前学期信息
        Page page = new Page(searchDto.getCurrentPage(),searchDto.getPageSize());
        IPage<Finish7sViewDto> viewDtoIPage = ise7sInspectMapper.selectByFinish7sSearchDto(page,searchDto,username,feedback);
        return viewDtoIPage;
    }

    /**
     * 查询7s检查详情(检查总表id查询)
     *
     * @param id
     * @return
     */
    @Override
    public Detail7sViewDto getDetail7sInspect(Long id) {
        //查询检查总表
        IseInspection inspection = iseInspectionMapper.selectById(id);
        //查询7s检查表
        Ise7sInspect ise7sInspect = ise7sInspectMapper.selectOne(new QueryWrapper<Ise7sInspect>().lambda()
                .eq(Ise7sInspect::getInspectId,id));
        Detail7sViewDto viewDto = new Detail7sViewDto();
        BeanUtils.copyProperties(ise7sInspect,viewDto);
        BeanUtils.copyProperties(inspection,viewDto);
        viewDto.setDutyNumber(inspection.getDutyTeacher());
        //查询老师表，拼接值班老师名字属性
        viewDto.setDutyName(cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber,inspection.getDutyTeacher())).getName());
        //查询实训室表
        BacTrainingRoom trainingRoom = trainingRoomMapper.selectById(inspection.getItemCheckId());
        BeanUtils.copyProperties(trainingRoom,viewDto);
        //查询老师表，拼接实训室管理人属性
        viewDto.setResponsibleName(cmsUserMapper.selectOne(new QueryWrapper<CmsUser>().lambda().eq(CmsUser::getNumber,trainingRoom.getResponsibleNumber())).getName());
        //拼接多个老师字符串
        viewDto.setTeaNumbers(dormInspectService.getTeachersStr(inspection.getTeachersNumbers()));
        viewDto.setId(ise7sInspect.getId());
        //查询图片
        IseImages images = imagesMapper.selectOne(new QueryWrapper<IseImages>().lambda().eq(IseImages::getInspectId,inspection.getId()));
        if (images!=null){
            viewDto.setImage(images.getAddress());
        }else {
            viewDto.setImage(null);
        }
        viewDto.setId(inspection.getId());
        System.out.println(viewDto.getImage());
        return viewDto;
    }


    /**
     * 填写7s反馈(检查总表id查询)
     *
     * @param feedBackAddDto
     * @return
     */
    @Override
    public Boolean addFeedback7sInspect(FeedBackAddDto feedBackAddDto) {
//        //查询对应7s检查表
//        Ise7sInspect ise7sInspect = ise7sInspectMapper.selectById(feedBackAddDto.getId());
//        if (ise7sInspect == null){
//            return false;
//        }
        //查询对应检查总表
        IseInspection inspection = iseInspectionMapper.selectById(feedBackAddDto.getId());
        if (inspection == null||inspection.getFeedbackStatus()==10){
            return false;
        }
        //获取当前登录用户编号
        String username = userSaveDetails.getCmsUser().getNumber();
        //获取责任人用户编号
        String feedbacker = trainingRoomMapper.selectById(inspection.getItemCheckId()).getResponsibleNumber();
        if (!username.equals(feedbacker)){
            return false;
        }

        inspection.setFeedbackStatus(20);
        inspection.setResult(feedBackAddDto.getResult());
        iseInspectionMapper.updateById(inspection);
        return true;
    }

    /**
     * 填写7s检查
     *
     * @param addDto
     * @return
     */
    @Override
    public Map<String,Object> add7sInspect(Ise7sInspectAddDto addDto) {
        Map<String,Object> trueAndMsg = new HashMap<>();
        trueAndMsg.put("success",false);
        //获取当前日期
        Date nowDate = JHC.removeTime(new Date());
        //查询值班人员
        String username = userSaveDetails.getCmsUser().getNumber();
        IseSchedule schedule = scheduleService.isSchedule(username,nowDate);
        //若不值班就返回false
        if (schedule == null){
            return trueAndMsg;
        }
        //查询检查对象列表，查看有无记录
        BacTrainingRoom trainingRoom = trainingRoomMapper.selectById(addDto.getId());
        if (trainingRoom==null){
            return trueAndMsg;
        }
        //查询检查总表，查看有无记录
        List<IseInspection> inspectionList = inspectionService.getInspections(nowDate,addDto.getId(),CheckType.ISE7S.getCode());
        if (inspectionList.size()>0){
            return trueAndMsg;
        }
        //遍历相关教师，校验数据
        addDto.setTeaNumbers(addDto.getTeaNumbers().stream().distinct().collect(Collectors.toList()));
        if (!cmsUserService.isUserNumberList(addDto.getTeaNumbers())){
            return trueAndMsg;
        }
        //构造检查总表插入对象
        InspectionCreateDto createDto = new InspectionCreateDto(schedule.getWeek(),nowDate,username, CheckType.ISE7S.getCode());
        BeanUtils.copyProperties(addDto,createDto);
        Map<String,Object> resultMap = inspectionService.addInspection(createDto,trainingRoom.getResponsibleNumber());
        IseInspection inspection = (IseInspection) resultMap.get("inspection");
        //构造7s检查表插入对象
        Ise7sInspect ise7sInspect = new Ise7sInspect();
        BeanUtils.copyProperties(addDto,ise7sInspect);
        ise7sInspect.setId(null);
        ise7sInspect.setInspectId(inspection.getId());
        ise7sInspect.setImage(null);
        ise7sInspectMapper.insert(ise7sInspect);
        //构造图片插入对象
        if (addDto.getImage()!=null&&StringUtils.isNotBlank(addDto.getImage())){
            IseImages iseImages = new IseImages();
            iseImages.setAddress(addDto.getImage());
            iseImages.setInspectId(inspection.getId());
            imagesMapper.insert(iseImages);
        }
        trueAndMsg.put("msgList",resultMap.get("msgList"));
        trueAndMsg.put("success",true);
        return trueAndMsg;
    }

    /**
     * 修改7s检查
     *
     * @param updateDto
     * @return
     */
    @Override
    public Map<String,Object> update7sInspect(Ise7sInspectUpdateDto updateDto) {
        //构造返回对象
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("success",false);
        resultMap.put("msg",null);
        //获取当前日期
        Date nowDate = JHC.removeTime(new Date());
        //查询值班人员
        String username = userSaveDetails.getCmsUser().getNumber();
        IseSchedule schedule = scheduleService.isSchedule(username,nowDate);
        //若不值班就返回false
        if (schedule == null){
            resultMap.put("msg","当前用户不值班");
            return resultMap;
        }
        //查询检查总表，查看是否有记录
        IseInspection iseInspection = iseInspectionMapper.selectById(updateDto.getInspectId());
        System.out.println(iseInspection);
        System.out.println(JHC.removeTime(iseInspection.getDutyDate()));
        System.out.println(nowDate);
        System.out.println(new Date());
        if (iseInspection == null||!iseInspection.getDutyDate().equals(nowDate)){
            resultMap.put("msg","该记录未检查");
            return resultMap;
        }
        //遍历相关教师，校验数据
        updateDto.setTeaNumbers(updateDto.getTeaNumbers().stream().distinct().collect(Collectors.toList()));
        if (updateDto.getTeaNumbers().size()!=0 && !cmsUserService.isUserNumberList(updateDto.getTeaNumbers())){
            resultMap.put("msg","相关教师无该用户");
            return resultMap;
        }
        //封装对象数据，更新数据
        BeanUtil.copyProperties(updateDto,iseInspection, CopyOptions.create().setIgnoreNullValue(true));
        iseInspection.setTeachersNumbers(JSON.toJSONString(updateDto.getTeaNumbers()));
        iseInspection.setDutyTeacher(username);
        iseInspection.setUpdateTime(null);
        iseInspectionMapper.updateById(iseInspection);
        //查询7s检查表
        Ise7sInspect ise7sInspect = ise7sInspectMapper.selectOne(new QueryWrapper<Ise7sInspect>().lambda()
                .eq(Ise7sInspect::getInspectId,iseInspection.getId()));
        if (ise7sInspect==null){
            resultMap.put("msg","该记录未检查");
            return resultMap;
        }
        BeanUtil.copyProperties(updateDto,ise7sInspect, CopyOptions.create().setIgnoreNullValue(true));
        ise7sInspect.setUpdateTime(null);
        ise7sInspectMapper.updateById(ise7sInspect);
        //查询检查图片
        if (updateDto.getImageAddress()==null||!StringUtils.isNotBlank(updateDto.getImageAddress())){
            resultMap.put("success",true);
            resultMap.put("msg","无图片");
            return resultMap;
        }
        IseImages images = imagesMapper.selectOne(new QueryWrapper<IseImages>().lambda()
                .eq(IseImages::getInspectId,iseInspection.getId()));
        if (images==null){
            images = new IseImages();
            images.setAddress(updateDto.getImageAddress());
            images.setInspectId(iseInspection.getId());
            imagesMapper.insert(images);
            resultMap.put("success",true);
            resultMap.put("msg","数据库插入图片");
            return resultMap;
        }
        images.setAddress(updateDto.getImageAddress());
        images.setUpdateTime(null);
        imagesMapper.updateById(images);
        resultMap.put("success",true);
        resultMap.put("msg","数据库更新图片");
        return resultMap;
    }

    /**
     * 查询7s数据分析
     *
     * @param searchDto
     * @return
     */
    @Override
    public Map<String, Object> getAnalysis(AnalysisSearchDto searchDto) {
        //构造返回对象
        Map<String,Object> resultMap = new HashMap<>();
        //获取当前用户信息
        CmsUser teacher = userSaveDetails.getCmsUser();
        //查询负责实训室
        List<BacTrainingRoom> roomList = trainingRoomMapper.selectList(new QueryWrapper<BacTrainingRoom>().lambda()
                .eq(BacTrainingRoom::getResponsibleNumber,teacher.getNumber()));
        if (roomList.size()==0){
            return resultMap;
        }
        //查询实训室的7s数据分析
        List<Analysis7sViewDto> viewDtoList = analysis7s(roomList,searchDto);
        //构建数据分析总表数据
        Analysis7sViewDto allViewDto = new Analysis7sViewDto();
        System.out.println(viewDtoList);
        viewDtoList.stream().forEach(viewDto -> {
            allViewDto.addAnalysisAll(viewDto);
        });
        resultMap.put("allAnalysis",allViewDto);
        resultMap.put("analysisList",viewDtoList);
        return resultMap;
    }

    /**
     * 计算7s的数据分析
     *
     * @param rooms
     * @param searchDto
     * @return
     */
    @Override
    public List<Analysis7sViewDto> analysis7s(List<BacTrainingRoom> rooms, AnalysisSearchDto searchDto) {
        //构造返回对象
        List<Analysis7sViewDto> viewDtoList = new ArrayList<>();
        rooms.stream().forEach(room -> {
            Analysis7sViewDto viewDto = new Analysis7sViewDto();
            //插入实训室信息
            viewDto.setRoomId(room.getId());
            viewDto.setRoomName(room.getRoomName());
            //查询检查总表
            List<Object> roomIds = new ArrayList<>();
            roomIds.add(room.getId());
            List<IseInspection> inspectionList = inspectionService.getInspections(searchDto.getStartDate(),searchDto.getEndDate(),roomIds,CheckType.ISE7S.getCode());
            List<Object> inspectIds = inspectionList.stream().map(item -> item.getId()).collect(Collectors.toList());
            if (inspectionList.size()==0){
                viewDtoList.add(viewDto);
                return;
            }
            //查询7s检查表
            List<Ise7sInspect> ise7sInspectList = ise7sInspectMapper.selectList(new QueryWrapper<Ise7sInspect>().lambda()
                    .in(Ise7sInspect::getInspectId,inspectIds));
            ise7sInspectList.stream().forEach(ise7sInspect -> {
                viewDto.addAnalysis(ise7sInspect);
            });
            viewDtoList.add(viewDto);
        });
        return viewDtoList;
    }
}
